package yuyicman.core 
{
	import flash.events.Event;
	import yuyicman.debug.Debugger;
	/**
	 * ...
	 * @author Yuyic.
	 */
	public class DestroyManager implements IDestroyManager 
	{
		
		public static const DESTROY:String = "destroy";
		
		private static var _instance:DestroyManager;
		private static var _array:Array;
		
		public function DestroyManager( single:Singleton ) 
		{
			_array = new Array();
		}
		
		public function addDestroy( destroy:IDestroy ):IDestroy {
			destroy.addEventListener( DestroyManager.DESTROY, onDestroyHandler, false, 0, true );
			_array.push( destroy );
			return destroy;
		}
		
		public function removeDestroy( destroy:IDestroy ):IDestroy {
			var i:int = _array.length - 1;
			var des:IDestroy;
			for (i; i >= 0; i--) {
				if (_array[i] == destroy) {
					des = _array[i];
					_array.splice(i, 1);
					break;
				}
			}
			return des;
		}
		
		public function destroyAll():void {
			for each( var destroy:IDestroy in _array ) {
				destroy.removeEventListener( DestroyManager.DESTROY, onDestroyHandler );
				destroy.destroy();
			}
			_array = new Array();
		}
		
		private function onDestroyHandler( e:Event ):void {
			
			removeDestroy( IDestroy(e.target) );
			
		}
		
		public static function get instance():DestroyManager {
			if ( _instance ==null ) {
				_instance = new DestroyManager( new Singleton );
			}
			return _instance;
		}
		
	}

}

internal class Singleton{}